package org.example.javachatroom.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.example.javachatroom.component.OnlineUserManager;
import org.example.javachatroom.mapper.FriendMapper;
import org.example.javachatroom.model.AddFriendRequest;
import org.example.javachatroom.model.Friend;
import org.example.javachatroom.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@RestController
public class FriendController {
    @Autowired
    private FriendMapper friendMapper;
    @Autowired
    private OnlineUserManager onlineUserManager;

    @Autowired
    private ObjectMapper objectMapper;

    @GetMapping("/friendList")
    @ResponseBody
    public Object getFriendList(HttpServletRequest request){
        //1、先从会话中，获取到userId是啥
        HttpSession session = request.getSession(false);
        if(session == null){
            //当前用户未登录
            //直接返回一个空列表即可
            System.out.println("[getFriendList] session不存在");
            return new ArrayList<Friend>();
        }
        User user = (User) session.getAttribute("user");
        if(user == null){
            //当前用户对象没在会话中存在
            System.out.println("[getFriendList] user不存在");
            return new ArrayList<Friend>();
        }
        //2、根据userId查询数据库
        List<Friend> friends = friendMapper.selectFriendList(user.getUserId());
        return friends;
    }

    /**
     * 查找未添加的好友
     * @param name
     * @param request
     * @return
     */
    @GetMapping("/findFriend")
    @ResponseBody
    public Object findFriend(String name,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            return friendMapper.findFriend(user.getUserId(),name);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return "";
    }
    /**
     * 添加好友进数据库表中
     * @param friendId
     * @param reason
     * @param request
     * @return
     */
    @GetMapping("/addFriend")
    @ResponseBody
    public Object addFriend(int friendId,String reason,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            System.out.println("[添加好友]"+user.getUserId()+","+friendId+","+reason);
            //写入数据库
            friendMapper.addFriendRequesy(user.getUserId(),friendId,reason);
            //发送websocket响应
            WebSocketSession webSocketSession = onlineUserManager.getSession(friendId);
            if(webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("addFriendRequest");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason(reason);
                //给对应的用户发送websocket请求，提示有用户尝试添加好友
                webSocketSession.sendMessage(
                        new TextMessage(
                                objectMapper.writeValueAsString(addFriendRequest)
                        ));
            }
        } catch (NullPointerException | IOException e) {
            e.printStackTrace();
        }
        return "";
    }

    /**
     * 获取添加好友请求（离线）
     * @param request
     * @return
     */
    @GetMapping("/getFriendRequest")
    @ResponseBody
    public Object getFriendRequest(HttpServletRequest request){
        List<AddFriendRequest> addFriendRequestList = new ArrayList<>();
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            addFriendRequestList = friendMapper.getFriendRequest(user.getUserId());
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return addFriendRequestList;
    }

    /**
     * 同意好友请求，由于涉及到多张表的修改，需要开启事务
     * @param friendId
     * @param request
     * @return
     */
    @GetMapping("/acceptFriend")
    @ResponseBody
    @Transactional
    public Object acceptFriend(int friendId,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            //1、删除好友请求表的存档
            friendMapper.deleteFriendRequest(friendId,user.getUserId());
            //2、修改好友表
            friendMapper.addFriend(friendId,user.getUserId());
            //3、通过websocket通知对方刷新好友列表
            WebSocketSession webSocketSession =
                    onlineUserManager.getSession(friendId);
            if(webSocketSession != null){
                AddFriendRequest addFriendRequest = new AddFriendRequest();
                addFriendRequest.setType("acceptFriend");
                addFriendRequest.setFromUserId(user.getUserId());
                addFriendRequest.setFromUserName(user.getUsername());
                addFriendRequest.setReason("");
                webSocketSession.sendMessage(new
                        TextMessage(objectMapper.writeValueAsString(addFriendRequest)));
            }
        }catch (NullPointerException | IOException e){
            e.printStackTrace();
        }
        return "";
    }

    @GetMapping("/rejectFriend")
    @ResponseBody
    public Object rejectFriend(int friendId,HttpServletRequest request){
        try{
            HttpSession session = request.getSession(false);
            User user = (User) session.getAttribute("user");
            //删除好友请求表的存档
            friendMapper.deleteFriendRequest(user.getUserId(), friendId);
        } catch (NullPointerException e) {
            e.printStackTrace();
        }
        return "";
    }
}
